﻿$(function () {
    loadMenu();
    getIndustry();
    getLocation();
    getPostedJob();
    getAppliedJob();
    getAllProvince();
    getJobtype();
    getJoblvl();
    getCurrentcy();
    
    getUniversity();
    getDegreeKind();
    getDegree();
    getMajor();

    getPersonalInfo();
    
    $('#myModal').on('hide.bs.modal', function () {
        $(this).find('#jobname').val('');
        $(this).find('#salary').val('');
        $(this).find('#_textareJD').val('');
        $(this).find('#_textareR').val('');
        $(this).find('#_competitive').prop('checked', false);
        $('#salary').prop('disabled', false);
        vm.LocationSelected('');
        vm.FunctionSelected('');
    });
    $("#_competitive").click(function () {
        if (this.checked) {
            $('#salary1').prop('disabled', true);
            $('#salary2').prop('disabled', true);
            $('#salary3').prop('disabled', true);
        } else {
            $('#salary1').prop('disabled', false);
            $('#salary2').prop('disabled', false);
            $('#salary3').prop('disabled', false);
        }
    });
    $("#m_competitive").click(function () {
        if (this.checked) {
            $('#msalary').prop('disabled', true);
        } else {
            $('#msalary').prop('disabled', false);
        }
    });
    

    $('.datepicker').datepicker({
        format: 'dd/mm/yyyy',
        weekStart: 1
    }).on('changeDate', function (ev) {
        var data = ko.dataFor($(this)[0]);
        data.Account.PersonalInfor().Birthday(ev.date);
    });

});


vm.Industry = ko.observableArray();
vm.Function = ko.observableArray();
vm.Location = ko.observableArray();
vm.Province = ko.observableArray();
vm.City = ko.observableArray();
vm.PostedJobs = ko.observableArray();
vm.AppliedJobs = ko.observableArray();
vm.JobType = ko.observableArray();
vm.JobLevel = ko.observableArray();

vm.IndustrySelected = ko.observable('');
vm.LocationSelected = ko.observable('');
vm.ProvinceSelected = ko.observable('');
vm.CitySelected = ko.observable('');
vm.FunctionSelected = ko.observable();
vm.Account = ko.observable();
vm.Currency = ko.observableArray();
vm.selectCurrency = ko.observable();

vm.IndustrySelected.subscribe(function (newValue) {
    if (typeof newValue != 'undefined') {
        vm.Function([]);
        var query = breeze.EntityQuery
                  .from('Industry')
                  .where('ParentId', '==', newValue);
        var functions = manager.executeQueryLocally(query);
        for (var i = 0; i < functions.length; i++){
            vm.Function.push(functions[i]);
        }
        

    } else {
        vm.Function([]);
    }
    
});
vm.LocationSelected.subscribe(function (newValue) {
    if (typeof newValue != 'undefined') {
        vm.Province([]);
        var query = breeze.EntityQuery
                  .from('Location')
                  .where('ParentId', '==', newValue);
        var provinces = manager.executeQueryLocally(query);
        for (var i = 0; i < provinces.length; i++) {
            vm.Province.push(provinces[i]);
        }


    } else {
        vm.Province([]);
    }

});
vm.ProvinceSelected.subscribe(function (newValue) {
    if (typeof newValue != 'undefined') {
        vm.City([]);
        var query = breeze.EntityQuery
                  .from('Location')
                  .where('ParentId', '==', newValue);
        var city = manager.executeQueryLocally(query);
        for (var i = 0; i < city.length; i++) {
            vm.City.push(city[i]);
        }


    } else {
        vm.City([]);
    }

});
vm.Save = function () {
    var salary1;
    var salary2 = '';
    var currency = null;
    if ($("#_competitive").is(':checked')) {
        salary1 = 'Competitive';
    } else {
        salary1 = $('#salary1').val().split(',').join('');
        salary2 = $('#salary2').val().split(',').join('');
        currency = vm.selectCurrency();
    }

    var newJob = manager.createEntity('Job', { 
        Name: $('#jobname').val(), 
        SalaryFrom: salary1,
        SalaryTo: salary2,
        CurrencyId: currency,
        Status: 1, 
        DatePost: new Date($.now()), 
        PersonalId: $.trim($('#_perid').text()),
        LocationId: vm.CitySelected(), 
        IndustryId: vm.IndustrySelected(), 
        Description: $('#_textareJD').val(),
        Requirement: $('#_textareR').val()
    });
    vm.PostedJobs.push(newJob);
    saveSingleEntity(newJob);
    var s = newJob.entityAspect.getValidationErrors();

    $('#myModal').modal('hide');
}
vm.infoSave = function () {
    var enitityArr = Array();
    var model = ko.dataFor($(this)[0]);
    enitityArr.push(vm.Account);
    enitityArr.push(vm.Account.PersonalInfor());
    saveSingleEntity(null, enitityArr);
}
vm.desSave = function () {
    saveSingleEntity(vm.Account.PersonalInfor(), null);
}

function getCurrentcy() {
    var qrAppliedJob = new breeze.EntityQuery().from("Currencies");
    manager.executeQuery(qrAppliedJob).then(function (data) {
        data.results.forEach(function (item) {
            vm.Currency.push(item);
        });
    }).fail(function (e) {
        alert(e);
    });
}
function getAppliedJob() {
    var qrAppliedJob = new breeze.EntityQuery().from("ApplyJobs").where("PersonalId", "==", $.trim($('#_perid').text()));
    manager.executeQuery(qrAppliedJob).then(function (data) {
        data.results.forEach(function (item) {
            item.Job().ApplyDate = item.ApplyDate();
            vm.AppliedJobs.push(item.Job());
        });
    }).fail(function (e) {
        alert(e);
    });
}
function getPostedJob() {

    var qrIndustry = new breeze.EntityQuery().from("Jobs").where("PersonalId", "==", $('#_perid').text());
    manager.executeQuery(qrIndustry).then(function (data) {
        data.results.forEach(function (item) {
            vm.PostedJobs.push(item);
        });
    }).fail(function (e) {
        alert(e);
    });
}
function getIndustry() {
    var qrIndustry = new breeze.EntityQuery().from("Industries").where("ParentId","==", null);
    manager.executeQuery(qrIndustry).then(function (data) {
        data.results.forEach(function (item) {
            vm.Industry.push(item);
        });
    }).fail(function (e) {
        alert(e);
    });
}
function getLocation(){
    var qrLocation = new breeze.EntityQuery().from("Locations").where("ParentId","==", null);
    manager.executeQuery(qrLocation).then(function (data) {
        data.results.forEach(function (item) {
            vm.Location.push(item);
        });
    }).fail(function (e) {
        alert(e);
    });
}
function getPersonalInfo() {
    var qrPersonalInfo = new breeze.EntityQuery().from("Accounts").where("UniqueId", "==", $('#_accid').text());
    manager.executeQuery(qrPersonalInfo).then(function (data) {
        data.results.forEach(function (item) {
            vm.Account = item;
            //body
            getEducation();
            ko.cleanNode($('#tmp')[0]);
            ko.applyBindings(vm, $('#tmp')[0]);
            addYear();
        });
    }).fail(function (e) {
        alert(e);
    });
}
function getJobtype() {
    var qrjobtype = new breeze.EntityQuery().from("JobTypes");
    manager.executeQuery(qrjobtype).then(function (data) {
        data.results.forEach(function (item) {
            vm.JobType.push(item);
        });
    }).fail(function (e) {
        alert(e);
    });
}
function getJoblvl() {
    var qrjoblvl = new breeze.EntityQuery().from("JobLevels");
    manager.executeQuery(qrjoblvl).then(function (data) {
        data.results.forEach(function (item) {
            vm.JobLevel.push(item);
        });
    }).fail(function (e) {
        alert(e);
    });
}

function getUniversity() {
    var qruniversity = new breeze.EntityQuery().from("Universitys");
    manager.executeQuery(qruniversity).then(function (data) {
        data.results.forEach(function (item) {
            vm.University.push(item);
        });
    }).fail(function (e) {
        alert(e);
    });
}
function getDegreeKind() {
    var qrdk = new breeze.EntityQuery().from("KindofDegrees");
    manager.executeQuery(qrdk).then(function (data) {
        data.results.forEach(function (item) {
            vm.DegreeKind.push(item);
        });
    }).fail(function (e) {
        alert(e);
    });
}
function getDegree() {
    var qrdk = new breeze.EntityQuery().from("Degrees");
    manager.executeQuery(qrdk).then(function (data) {
        data.results.forEach(function (item) {
            vm.Degree.push(item);
        });
    }).fail(function (e) {
        alert(e);
    });
}
function getMajor() {
    var qrdk = new breeze.EntityQuery().from("Majors");
    manager.executeQuery(qrdk).then(function (data) {
        data.results.forEach(function (item) {
            vm.Major.push(item);
        });
    }).fail(function (e) {
        alert(e);
    });
}
function addYear() {
    for (var i = 1950; i <= 2050; i++){
        $('.needyear').append("<option value = '" + i + "' >" + i + "</option>");
    }

    var currentyear = new Date().getFullYear();
    $(".needyear").val(currentyear);
}

function _downloadcv() {
    $.ajax({
        type: "Post",
        url: "../Employer/DownloadCV",
        data: {id : vm.Account.PersonalInfor().UniqueId()},
        success: function(msg)
        {
            alert(msg);
        }
    });

}

//Career expectation
vm.ceIndustry = ko.observable();
vm.ceFunction = ko.observable('');
vm.ceLevel = ko.observable('');
vm.ceCountry = ko.observable('');
vm.ceJobtype = ko.observable('');
vm.ceFunc = ko.observableArray();

vm.selectCareer = ko.observable('');

vm.ceIndustry.subscribe(function (newValue) {   
    vm.ceFunc([]);
    if (typeof newValue != 'undefined') {
        validateCareer();
        var query = breeze.EntityQuery
              .from('Industry')
              .where('ParentId', '==', newValue);
        var functions = manager.executeQueryLocally(query);
        for (var i = 0; i < functions.length; i++) {
            vm.ceFunc.push(functions[i]);
        }
    }  
});
vm.ceFunction.subscribe(function (newValue) {
    validateCareer();
});
vm.ceLevel.subscribe(function (newValue) {
    validateCareer();
});
vm.ceCountry.subscribe(function (newValue) {
    validateCareer();
});
vm.ceJobtype.subscribe(function (newValue) {
    validateCareer();
});

vm.addCareerExpect = function () {
    if (!validateCareer()) {
        return;
    }
    var newExpect = manager.createEntity('CareerExpect', {
            Title: $.trim($('#_jobtitle').val()),
            SalaryFrom: $.trim($('#_sf').val()),
            SalaryTo: $.trim($('#_st').val()),
            LocationId: vm.ceCountry(),
            IndustryId: vm.ceFunction(),
            JobLevelId: vm.ceLevel(),
            JobTypeId: vm.ceJobtype(),
            PersonalId: vm.Account.PersonalId(),
            Note: $.trim($('#_cenote').val())
    });

    saveSingleEntity(newExpect, null);
    clearExpect();
}
vm.delCareer = function () {
    if (jQuery.type(vm.selectCareer) === "function") return;
    var comd = confirm("Are you sure?");
    if (comd) {
        vm.Account.PersonalInfor().CareerExpect.remove(vm.selectCareer);
        vm.selectCareer.entityAspect.setDeleted();
        saveSingleEntity(vm.selectCareer, null);
    }
}
vm.onclick = function (item, event) {
    vm.selectCareer = ko.dataFor($(event.currentTarget)[0]);
    $(event.currentTarget).addClass('active').siblings().removeClass('active');
}

function validateCareer() {
    var valid = true;
    $('.validate').each(function () {
        if ($.trim($(this).val()) == '') {
            $(this).css('border-color', 'red');
            valid = false;
        } else {
            $(this).css('border-color', '');
        }
    });
    return valid;
}

function clearExpect() {
    $('#_jobtitle').val('');
    $('#_sf').val('');
    $('#_st').val('');
    $('#_cenote').val('');

    vm.ceCountry('');
    vm.ceIndustry('');
    vm.ceLevel('');
    vm.ceJobtype('');
    validateCareer();
}
function clearEdu() {
    $('#_enote').val('');
    var currentyear = new Date().getFullYear();
    $(".needyear").val(currentyear);
    $('#_emajor').val('');
    $('#_eUni').val('');
    $('#_eDegree').val('');
    $('#_eKdegree').val('');
    validateEdu();
}
function clearWE() {
    var currentyear = new Date().getFullYear();
    $(".needyear").val(currentyear);
    vm.weIndustry('');
    $('#_wecn').val('');
    $('#_wejt').val('');
    $('#_wea').val('');
    $('#_wefunc').val('');
    validateWE();
}



//Education
vm.University = ko.observableArray();
vm.DegreeKind = ko.observableArray();
vm.Degree = ko.observableArray();
vm.Major = ko.observableArray();
vm.selectEdu = ko.observable('');

vm.Educationlist = ko.observableArray();

function getEducation() {
    for (var i = 0; i < vm.Account.PersonalInfor().Education().length; i++){
        vm.Educationlist.push(vm.Account.PersonalInfor().Education()[i]);
    }
}
vm.addEducation = function () {
    if (!validateEdu()) return;
    var newEducation = manager.createEntity('Education', {
        StartDate: $.trim($('#_start').val()),
        EndDate: $.trim($('#_end').val()),
        Note: $.trim($('#_enote').val()),
        PersonalId: vm.Account.PersonalId(),
        MajorId: $('#_emajor').val(),
        UniversityId: $('#_eUni').val(),
        DegreeId: $('#_eDegree').val(),
        KindofDegreeId: $('#_eKdegree').val(),
    });
    vm.Educationlist.push(newEducation);
    saveSingleEntity(newEducation, null);
    clearEdu(); 
}
function validateEdu() {
    var valid = true;
    $('.validateEdu').each(function () {
        if ($.trim($(this).val()) == '') {
            $(this).css('border-color', 'red');
            valid = false;
        } else {
            $(this).css('border-color', '');
        }
    });
    return valid;
}
vm.eduOnclick = function (item, event) {
    vm.selectEdu = ko.dataFor($(event.currentTarget)[0]);
    $(event.currentTarget).addClass('active').siblings().removeClass('active');
}
vm.delEducation = function () {
    if (jQuery.type(vm.selectEdu) === "function") return;
    var comd = confirm("Are you sure?");
    if (comd) {
        vm.Educationlist.remove(vm.selectEdu);
        vm.selectEdu.entityAspect.setDeleted();
        saveSingleEntity(vm.selectEdu, null);
    }
}



//Work experince
function getAllProvince() {
    var qrProvince = new breeze.EntityQuery().from("Locations").where("Parent.ParentId", "!=", null);
    manager.executeQuery(qrProvince).then(function (data) {
        data.results.forEach(function (item) {
            vm.weProvince.push(item);
        });
    }).fail(function (e) {
        alert(e);
    });
}

vm.selectWE = ko.observable('');
vm.weIndustry = ko.observable();
vm.weFunc = ko.observableArray();
vm.weProvince = ko.observableArray();

vm.weIndustry.subscribe(function (newValue) {
    vm.weFunc([]);
    if (typeof newValue != 'undefined') {
        var query = breeze.EntityQuery
              .from('Industry')
              .where('ParentId', '==', newValue);
        var functions = manager.executeQueryLocally(query);
        for (var i = 0; i < functions.length; i++) {
            vm.weFunc.push(functions[i]);
        }
    }
    
});
vm.WEOnclick = function (item, event) {
    vm.selectWE = ko.dataFor($(event.currentTarget)[0]);
    $(event.currentTarget).addClass('active').siblings().removeClass('active');
}
function validateWE() {
    var valid = true;
    $('.validateWE').each(function () {
        if ($.trim($(this).val()) == '') {
            $(this).css('border-color', 'red');
            valid = false;
        } else {
            $(this).css('border-color', '');
        }
    });
    return valid;
}

vm.addWExperiene = function () {
    if (!validateWE()) return;
    var newWE = manager.createEntity('WorkExperience', {
        CompanyName: $.trim($('#_wecn').val()),
        JobTitle: $.trim($('#_wejt').val()),
        Achieve: $.trim($('#_wea').val()),
        CurrentJob: $('input[name=currentjob]:checked', '#_radio').val(),
        LocationId: $.trim($('#_weprovince').val()),
        JobLevelId: $.trim($('#_welvl').val()),
        IndustryId: $.trim($('#_wefunc').val()),
        PersonalId: vm.Account.PersonalId()
    });
    saveSingleEntity(newWE, null);
    clearWE();
}
vm.delWE = function () {
    if (jQuery.type(vm.selectWE) === "function") return;
    var comd = confirm("Are you sure?");
    if (comd) {
        vm.Account.PersonalInfor().WorkExperience.remove(vm.selectWE);
        vm.selectWE.entityAspect.setDeleted();
        saveSingleEntity(vm.selectWE, null);
    }
}

